<?php

namespace App\Http\Controllers;

use App\Models\RedAccess;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SendAccessController extends Controller
{
    /**
     * 列表
     */
    public function index()
    {
        $RedAccess = RedAccess::orderBy('id','desc')->get();
        if($RedAccess) {
            foreach($RedAccess as $item) {
                $item->member;
            }
        }
        return response(['data'=>$RedAccess]);
    }

    /**
     * 添加
     */
    public function store(Request $request)
    {
        $_data = Validator::make(
            $request->all(),
            [
                'member_id' => [
                    'required',
                    'exists:members,id'
                ]
            ],
            [
                'member_id.required' => 'member_id不能为空',
                'member_id.exists' => '用户不存在'
            ]
        )->validate();
        try {
            if(RedAccess::where('member_id',$_data['member_id'])->exists()) {
                throw new \Exception('当前用户已经可以发红包了', 402);
            }
            if(RedAccess::create($_data)) {
                return response(['data'=>'success']);
            } else {
                throw new \Exception('操作失败',402);
            }
        } catch (\Exception $e) {
            return response(['message'=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     * 删除
     */
    public function destroy($_id)
    {
        if(RedAccess::destroy($_id)) {
            return response(['data'=>'success']);
        } else {
            return response(['message'=>'删除失败']);
        }
    }
}
